﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace EnterpriseInformation.Common
{
    public class CommonClass
    {

        public static string GetUrlParam(string url,string key)
        {
            if (url == null)
            {
                return "";
            }
            if (!url.Contains("http"))
            {
                url = "http://www.baidu.com/a" + url;
            }
            try
            {
                var uri = new Uri(url);
                var collection = HttpUtility.ParseQueryString(uri.Query);
                return collection[key];
            }
            catch (Exception)
            {
                return  "";
            }
        }
        public static string UrlEncode(string data)
        {
            if (data == null)
            {
                return "";
            }
            return System.Web.HttpUtility.UrlEncode(data, System.Text.Encoding.UTF8).Replace("%3A", ":").Replace("%2F", "/").Replace("+", "%20");



        }
        public static HtmlDocument HelperHtmlNode(HtmlDocument Ohtmlnode)
        {
            try
            {
                foreach (var script in Ohtmlnode.DocumentNode.Descendants("script").ToArray())
                    script.Remove();
                foreach (var style in Ohtmlnode.DocumentNode.Descendants("style").ToArray())
                    style.Remove();

                //string regexstr = @"<script[^>]*>([\s\S](?!<script))*?</script>";
                //resultDetail.Html = Regex.Replace(resultDetail.Html, regexstr, string.Empty, RegexOptions.IgnoreCase);

                HtmlNodeCollection basicRows = Ohtmlnode.DocumentNode.SelectNodes("//a");
                if (basicRows != null)
                {
                    foreach (var item in basicRows)
                    {
                       
                        if (item.InnerText.Contains("关注") || item.InnerText.Contains("收藏") || item.InnerText.Contains("下载")
                            || item.InnerText.Contains("股权链") || item.InnerText.Contains("投资链")
                            )
                        {
                            item.Remove();
                        }

                        var onclickT = item.Attributes["onclick"];
                        if (onclickT != null)
                        {
                         
                            if ( onclickT.Value.Contains("traJump") || onclickT.Value.Contains("信息纠错") || onclickT.Value.Contains("showReportModal")
                                || onclickT.Value.Contains("getGrouplist") || onclickT.Value.Contains("caseDetailView") || onclickT.Value.Contains("addcaseFav") || onclickT.Value.Contains("addRadar")
                                || onclickT.Value.Contains("oneStepFollow")  || onclickT.Value.Contains("showHisTel") || onclickT.Value.Contains("samefieldlist") || onclickT.Value.Contains("showReportAddress")
                                || onclickT.Value.Contains("indirectinvestmentView") || onclickT.Value.Contains("showDetailModel") || onclickT.Value.Contains("showSVipModal")
                                 )
                            {
                                item.Remove();
                            }
                            if (onclickT.Value.Contains("jumpHistory"))
                            {
                                item.ParentNode.Remove();
                            }
                            if (onclickT.Value.Contains("xzcfView")  || onclickT.Value.Contains("spledgeView") 
                                || onclickT.Value.Contains("envDetail") || onclickT.Value.Contains("overseadetail") || onclickT.Value.Contains("gdczView") || onclickT.Value.Contains("stockView") 
                                || onclickT.Value.Contains("caseDetailView") || onclickT.Value.Contains("addcaseFav") || onclickT.Value.Contains("showRelatModal") || onclickT.Value.Contains("showSamePenalty")
                                || onclickT.Value.Contains("usercomplaintDetail") || onclickT.Value.Contains("taxIllegalDetail") || onclickT.Value.Contains("oweNoticeDetail") || onclickT.Value.Contains("mPledgeView")
                                || onclickT.Value.Contains("pnDetail") || onclickT.Value.Contains("creditorDetail") || onclickT.Value.Contains("telecomDetail")
                                )
                            {
                                item.Attributes.Remove("href");
                                item.Attributes.Remove("onclick");
                            }
                        }
                        

                        var ids = item.Attributes["id"];
                        if (ids != null)
                        {
                            if (ids.Value.Contains("exportBtn"))
                            {
                                item.Remove();
                            }
                        }
                        var href = item.Attributes["href"];
                        string uul = string.Empty;
                        if (href != null)
                        {
                            if (href == null)
                            {
                                item.Attributes.Remove("target");
                            }
                            else if (href != null)
                            {
                                if (!href.Value.Contains("javascript") && !href.Value.Contains("#"))
                                {
                                    item.SetAttributeValue("target", "_blank");

                                }
                                else if (href.Value.Contains("javascript") || href.Value.Contains("#"))
                                {
                                    item.Attributes.Remove("target");
                                }
                            }

                            if (href.Value.Contains("https://z.qcc.com/") || href.Value.Contains("https://t.qcc.com/search") || href.Value.Contains("/own_") || href.Value.Contains("/map?")
                                || href.Value.Contains("/bene-breakthrough?") || href.Value.Contains("https://y.qcc.com") || href.Value.Contains("/company_guquanperson")
                                || href.Value.Contains("https://pro.qcc.com/")
                                    )
                            {
                                item.Remove();
                            }
                            
                            ///pl.html?keyNo=a40d4b905891f5fb59ee6eb794eeeaee&name=马云
                            if (href.Value.Contains("/pl/"))
                            {
                                string keyno = href.Value.Replace("/pl/", "").Replace(".html", "");
                                if (keyno.Substring(0, 1) == "p")
                                {
                                    uul = $"/static/pl.html?keyNo={href.Value.Replace("/pl/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";

                                }
                                else
                                {
                                    uul = $"/static/firm.html?keyNo={href.Value.Replace("/pl/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";

                                }
                                item.SetAttributeValue("keyno", keyno);
                                item.SetAttributeValue("href", uul);
                            }
                            ///firm.html?keyNo=a40d4b905891f5fb59ee6eb794eeeaee&companyname=深圳市创海数码有限公司
                            if (href.Value.Contains("/firm/"))
                            {
                                string keyno = href.Value.Replace("/firm/", "").Replace(".html", "");
                                if (keyno.Substring(0,1) == "p")
                                {
                                    uul = $"/static/pl.html?keyNo={href.Value.Replace("/firm/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";

                                }
                                else
                                {
                                    uul = $"/static/firm.html?keyNo={href.Value.Replace("/firm/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";

                                }
                                item.SetAttributeValue("keyno", keyno);
                                item.SetAttributeValue("href", uul);
                            }
                            ///risk_cooperate?unique=84c17a005a759a5e0d875c1ebb6c9846&obj=-1
                            if (href.Value.Contains("/risk_cooperate?"))
                            {
                                uul = $"/static/risk_cooperate.html?{href.Value.Substring(href.Value.IndexOf('?') + 1).Replace("unique", "keyNo")}";
                                item.SetAttributeValue("href", uul);
                                if (!item.InnerText.Contains("风险") && !item.InnerText.Contains("详情"))
                                {
                                    item.Attributes.Remove("target");
                                }
                            }

                            if (href.Value.Contains("/deadbeat/"))
                            {
                                uul = $"/static/deadbeat.html?keyNo={href.Value.Replace("/deadbeat/", "").Replace(".html", "")}&name={item.InnerText.Replace(" ","").Replace("\\n","")}";
                                item.SetAttributeValue("keyno", href.Value.Replace("/deadbeat/", "").Replace(".html", ""));
                                item.SetAttributeValue("href", uul);
                            }
                            if (href.Value.Contains("/case/"))
                            {
                                uul = $"/static/case.html?keyNo={href.Value.Replace("/case/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";
                                item.SetAttributeValue("keyno", href.Value.Replace("/case/", "").Replace(".html", ""));
                                item.SetAttributeValue("href", uul);
                            }
                            if (href.Value.Contains("/wenshuDetail/"))
                            {
                                uul = $"/static/wenshuDetail.html?keyNo={href.Value.Replace("/wenshuDetail/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";
                                item.SetAttributeValue("keyno", href.Value.Replace("/wenshuDetail/", "").Replace(".html", ""));
                                item.SetAttributeValue("href", uul);
                            }

                            if (href.Value.Contains("/shixinDetail/"))
                            {
                                uul = $"/static/shixinDetail.html?keyNo={href.Value.Replace("/shixinDetail/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";
                                item.SetAttributeValue("keyno", href.Value.Replace("/shixinDetail/", "").Replace(".html", ""));
                                item.SetAttributeValue("href", uul);
                            }
                            if (href.Value.Contains("/zhixingDetail/"))
                            {
                                uul = $"/static/zhixingDetail.html?keyNo={href.Value.Replace("/zhixingDetail/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";
                                item.SetAttributeValue("keyno", href.Value.Replace("/zhixingDetail/", "").Replace(".html", ""));
                                item.SetAttributeValue("href", uul);
                            }


                            if (href.Value.Contains("/product/") || href.Value.Contains("/zhuanliDetail/") || href.Value.Contains("/postnews_") || href.Value.Contains("/tenderDetail/")
                                || href.Value.Contains("/investor/") || href.Value.Contains("https://news.qcc.com")  || href.Value.Contains("/jobdetail/") || href.Value.Contains("/more_gov?") 
                                || href.Value.Contains("/postnews/") || href.Value.Contains("/brandDetail/") || href.Value.Contains("/announcementdetail/") || href.Value.Contains("/xiangaoDetail/")
                                || href.Value.Contains("/web/bd/")
                                )
                            {
                                item.Attributes.Remove("target");
                                item.Attributes.Remove("href");
                            }
                            if (href.Value.Contains("/risk?") )
                            {
                                item.SetAttributeValue("href", href.Value.Replace(".html", "").Replace("/risk?", "/static/risk.html?"));
                            }
                            if (href.Value.Contains("/dl_"))
                            {
                                item.SetAttributeValue("href", href.Value.Replace(".html", "").Replace("/dl_", "/static/dl.html?keyNo="));
                            }
                            if (href.Value.Contains("/dlr_"))
                            {
                                item.SetAttributeValue("href", href.Value.Replace(".html", "").Replace("/dlr_", "/static/dlr.html?keyNo="));
                            }
                            if (href.Value.Contains("/snapshoot/"))
                            {
                                uul = $"/static/snapshoot.html?keyNo={href.Value.Replace("/snapshoot/", "").Replace(".html", "")}&name={item.InnerText.Trim().Replace(" ", "").Replace("\\n", "")}";
                                item.SetAttributeValue("keyno", href.Value.Replace("/snapshoot/", "").Replace(".html", ""));
                                item.SetAttributeValue("href", uul);
                            }
                        }


                        

                    }
                }

                //水印，vip提醒
                HtmlNodeCollection basicRowspans = Ohtmlnode.DocumentNode.SelectNodes("//span[@class=\"watermark\"]|//span[contains(@class,\"vip\")]");
                if (basicRowspans != null)
                {
                    for (int i = 0; i < basicRowspans.Count; i++)
                    {
                        //basicRowspans.Remove(basicRowspans[i]);
                        basicRowspans[i].Remove();
                    }
                }
                //SPAN
                HtmlNodeCollection basicRowexportTables = Ohtmlnode.DocumentNode.SelectNodes("//span");
                if (basicRowexportTables != null)
                {
                    for (int i = 0; i < basicRowexportTables.Count; i++)
                    {
                        var isok = basicRowexportTables[i].Attributes["onclick"]?.Value;
                        if (isok != null && isok.Contains("exportTable"))
                        {
                            //basicRowexportTables.Remove(basicRowexportTables[i]);
                            basicRowexportTables[i].Remove();
                        }
                        else if (isok != null && isok.Contains("addNotice"))
                        {
                            //doc.DocumentNode.SelectNodes("//span").Remove(basicRowexportTables[i]);
                            basicRowexportTables[i].Remove();
                        }
                        else if (isok != null && isok.Contains("explainToCertModal"))
                        {
                            //doc.DocumentNode.SelectNodes("//span").Remove(basicRowexportTables[i]);
                            basicRowexportTables[i].Remove();
                        }
                        else if (isok != null && isok.Contains("addTenterNotice"))
                        {
                            //doc.DocumentNode.SelectNodes("//span").Remove(basicRowexportTables[i]);
                            basicRowexportTables[i].Remove();
                        }
                        else if (isok != null && isok.Contains("tagsClick"))
                        {
                            basicRowexportTables[i].Attributes.Remove("onclick");
                        }
                    }
                }


                HtmlNodeCollection riskgraphs = Ohtmlnode.DocumentNode.SelectNodes("//section[@id=\"riskgraph\"] | //section[@id=\"guquan\"] | //section[@id=\"kzrtupu\"] | //section[@id=\"muhou\"] | //section[@id=\"summarytext\"] | //div[@class=\"nco-bottom\"] | //footer  | //a[@id=\"radarIng\"]");
                if (riskgraphs != null)
                {
                    for (int i = 0; i < riskgraphs.Count; i++)
                    {
                        riskgraphs[i].Remove();
                    }
                }
                HtmlNodeCollection divs = Ohtmlnode.DocumentNode.SelectNodes("//div[@id=\"industryAnalysisChart\"] | //div[@id=\"financialAnalysisChart\"]");
                if (divs != null)
                {
                    for (int i = 0; i < divs.Count; i++)
                    {
                        var style = Regex.Replace(divs[i].Attributes["style"]?.Value, "width.*?px", "width: 960px"); ;
                        divs[i].SetAttributeValue("style", style);
                    }
                }
                HtmlNodeCollection imgs = Ohtmlnode.DocumentNode.SelectNodes("//img");
                if (imgs != null)
                {
                    for (int i = 0; i < imgs.Count; i++)
                    {
                        var isok = imgs[i].Attributes["src"]?.Value;
                        //if (isok != null && isok.Contains("chacha/cms/v2/images/nno_image.png"))
                        //{
                        //    imgs[i].SetAttributeValue("src", "/static/assets/images/nno_image.png");
                        //}
                        if (isok != null && isok.Contains("/chacha/cms/v2/images/"))
                        {
                            string tempsrc = isok.Substring(isok.IndexOf("images/") + 7);
                            imgs[i].SetAttributeValue("src", "/static/assets/images/" + tempsrc);
                        }
                        if (isok != null && isok.Contains("nno_image.png"))
                        {
                            imgs[i].SetAttributeValue("src", "/static/assets/images/no_data.png");
                        }
                    }
                }
                HtmlNode ipotitle = Ohtmlnode.DocumentNode.SelectSingleNode("//a[@id=\"ipo_title\"]");
                if (ipotitle != null)
                {
                    ipotitle.ParentNode.Remove();
                }



                return Ohtmlnode;
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 增加Cookie到CookieContainer      
        /// <param name="cookieContainer"></param>
        /// <param name="cookieName"></param>
        /// <param name="cookieValue"></param>
        /// <param name="path"></param>
        /// <param name="domain"></param>
        public static void AddCookie(CookieContainer cookieContainer,
            string cookieName, string cookieValue, string domain)
        {
            try
            {
                Cookie cookie = new Cookie(cookieName, cookieValue);

                cookieContainer.Add(new Uri(domain), cookie);

            }
            catch (Exception ex)
            {
            }
        }

        public static int GetRandom(int min, int max)
        {
            Random random = new Random(GetRandomSeed());
            return random.Next(min, max);
        }


        public static int GetRandomSeed()
        {
            byte[] data = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(data);
            return BitConverter.ToInt32(data, 0);
        }
    }
}
